var rowObject = undefined;

$(function() {

	if (typeof (InitForm) == "function") {
		InitForm();
	}
});

function SubmitForm() {
	var formObj = $("form");
	if (formObj.length == 0) {
		Alert("页面缺少必要的form标签");
		return false;
	}
	
	var action = "";
	if(typeof FormSubmitAction != "undefined")
	{
		action = FormSubmitAction
	}

	$.ajax({
		type : "POST",
		url : FormCodeUrl + "?method=" + FormSubmitMethod + "&action=" + action,
		data : formObj.serialize(),
		success : function(msg) {

			ReturnValue(msg);
		}

	});
}

function DeleteForm(selectArray) {
	var ret = "";
	
	var formObj = $("form");
	if (formObj.length == 0) {
		Alert("页面缺少必要的form标签");
		return false;
	}
	var searchObj = formObj.serialize();
	if (searchObj.length > 0) {
		searchObj += "&"
	}

	var selectItem = "";
	for (var i = 0; i < selectArray.length; i++) {
		if (i > 0) {
			selectItem += ",";
		}
		selectItem += selectArray[i];
	}

	$.ajax({
		type : "POST",
		async : false,
		url : FormCodeUrl + "?method=" + FormDeleteMethod + "&selectitem="
				+ selectItem,
		data : searchObj,
		success : function(msg) {
			ret = msg;
		}

	});

	return ret;
}

function SearchPage(pageIndex) {

	var formObj = $("form");
	if (formObj.length == 0) {
		Alert("页面缺少必要的form标签");
		return false;
	}

	var searchObj = formObj.serialize();
	if (searchObj.length > 0) {
		searchObj += "&"
	}
	searchObj += ("pageIndex=" + pageIndex);
	searchObj += ("&pageSize=" + TablePageSize);

	if (rowObject == undefined) {
		rowObject = $("#" + FormTableId + " tr:last").clone();
	}

	$
			.ajax({
				type : "POST",
				url : FormCodeUrl + FormQuery,
				data : searchObj,
				success : function(msg) {

					if (msg != undefined && msg.length > 0) {

						// window.clipboardData.setData("Text",msg);//设置数据
						try {
							// alert(msg);
							var retObj = eval("(" + msg + ")");

							$("#" + FormTableId + " tr[class=showDataRow]")
									.remove();

							for (var r = 0; r < retObj.list.length; r++) {
								var currentObj = rowObject.clone();

								currentObj.css("display", "");
								var tdArr = currentObj.find("td");
								for (var c = 0; c < tdArr.length; c++) {
									var text = tdArr.eq(c).html();
									if (text.length > 0) {
										tdArr.eq(c).html(ProcessLabel(retObj.list[r], text));
									}
								}

								currentObj.appendTo("#" + FormTableId);
							}

							// 处理分页
							$("#displayPage")
									.load(
											RootPath
													+ "/components/displaypage/pager",
											function(response, status) {
												if (status == "success") {
													var dpObj = $(response);
													dpObj.find("#fontTotal")[0].innerText = retObj.total;
													dpObj.find("#fontIndex")[0].innerText = retObj.pageNum;
													dpObj
															.find("#fontPageTotal")[0].innerText = retObj.pages;
													dpObj.find("#txtDP")[0].value = retObj.pageNum;

													var pageNum = parseInt(retObj.pageNum);
													var pages = parseInt(retObj.pages);
													var dpButton1 = dpObj
															.find("#btnDP1")[0];
													var dpButton2 = dpObj
															.find("#btnDP2")[0];
													var dpButton3 = dpObj
															.find("#btnDP3")[0];
													var dpButton4 = dpObj
															.find("#btnDP4")[0];
													var dpSelectPageSize = dpObj
															.find("#lstPageSize");
													var dpPageIndex = dpObj
															.find("#txtDP");
													var dpButton5 = dpObj
															.find("#btnDP5");

													dpButton1.disabled = false;
													dpButton2.disabled = false;
													dpButton3.disabled = false;
													dpButton4.disabled = false;
													
													if (pageNum <= 1) {
														dpButton1.disabled = true;
														dpButton2.disabled = true;
														//dpButton3.disabled = false;
														//dpButton4.disabled = false;
													}
													if (pageNum >= pages) {
														//dpButton1.disabled = false;
														//dpButton2.disabled = false;
														dpButton3.disabled = true;
														dpButton4.disabled = true;
													}

													dpButton1.onclick = function() {
														SearchPage(1);
													}
													dpButton2.onclick = function() {
														SearchPage(pageNum - 1);
													}
													dpButton3.onclick = function() {
														SearchPage(pageNum + 1);
													}
													dpButton4.onclick = function() {
														SearchPage(pages);
													}
													dpSelectPageSize
															.val(TablePageSize);
													dpSelectPageSize
															.change(function() {
																var pageSize = $(
																		this)
																		.children(
																				'option:selected')
																		.val();
																TablePageSize = pageSize;
																SearchPage(1);
															});

													dpButton5
															.click(function() {

																if (isNaN(dpPageIndex
																		.val())) {
																	dpPageIndex
																			.val(1);
																	SearchPage(1);
																} else {
																	var pi = parseInt(dpPageIndex
																			.val());
																	if (pi <= 0) {
																		dpPageIndex
																				.val(1);
																		pi = 1;
																	} else if (pi >= pages) {
																		dpPageIndex
																				.val(pages);
																		pi = pages
																	}
																	SearchPage(pi);
																}
															});

													$("#displayPage").html("");
													$("#displayPage").append(
															dpObj);
												}
											});
							
							//处理上移下移按钮
							if(pageIndex==1)
							{
								var upButton=$(".upButton:first");
								upButton.css("visibility","hidden");
							}
							if(pageIndex==retObj.pages)
							{
								var downButton=$(".downButton:last");
								downButton.css("visibility","hidden");
							}

						} catch (e) {
							$("#" + FormTableId + " tr[class=showDataRow]")
									.remove();
							alert(e.message);
						}
					} else {
						$("#" + FormTableId + " tr[class=showDataRow]")
								.remove();
					}
				}
			});
}

function upAndDown(action,dbName,tableName,keyFieldName,keyId,refKeyId,sortFieldName,value,refValue)
{
	$.ajax({
		type : "POST",
		async : false,
		url : RootPath + "/base" + "?method=processOrder&action="+action+"&keyId="+keyId+"&refKeyId="+refKeyId+"&value="+value+"&refValue="+refValue+"&dbName="+dbName+"&tableName="+tableName+"&keyFieldName="+keyFieldName+"&sortFieldName="+sortFieldName,
		success : function(msg) {
			
			var retObj = eval("(" + msg + ")");
			var pageIndex=0;
			try
			{
				pageIndex=$("#fontIndex").text()
			}
			catch(e)
			{
				pageIndex=1;
			}
			
			if(retObj.result=="1")
			{
				SearchPage(pageIndex);
			}
			else
			{
				alert(retObj.message);
			}
			
		}

	});
}


function ProcessLabel(obj, text) {
	// text = text.replace("{", "").replace("}", "").replace(" ", "");

	var startIndex = text.indexOf("{");
	var endIndex = text.indexOf("}", startIndex);

	while (startIndex > -1 && endIndex > -1 && endIndex - startIndex > 1) {
		var label = text.substring(startIndex + 1, endIndex);

		var labelAfter = "";
		try {
			eval("labelAfter=obj." + label + ";");
		} catch (e) {

		}
		if(labelAfter==undefined)
		{
			labelAfter="";
		}
		
		text = text.replace(text.substring(startIndex, endIndex + 1),labelAfter);

		startIndex = text.indexOf("{");
		endIndex = text.indexOf("}", startIndex);
	}

	return text;
}

function CloseWindow() {
	parent.CloseDialog();
}

function OpenWindow(url, title, width, height, flag, success, error) {

	CommonDialog(url, title, width, height, function(v) {
		if (v == flag) {

			$("#dialog .container").load(function() {
				Success(success, function() {
					location.href = location.href;
				});
			});
		} else {

			$("#dialog .container").load(function() {
				Alert(error);
			});
		}
	});
}
function ReturnValue(v) {
	if ("undefined" != typeof ReturnDialogValue) {
		ReturnDialogValue(v);
	}
}

function InitForm() {

	// 表单验证机制
	var checkObj = $(".inputresult");
	var checkNumber = checkObj.length;
	if (checkNumber > 0) {
		checkObj.each(function(index, obj) {

			obj = $(obj);
			CheckControl(obj, "blur");
			// CheckControl(obj, "change");

		});
	}
}

function CheckForm() {

	var ret = true;

	var checkObj = $(".inputresult");
	var checkNumber = checkObj.length;
	if (checkNumber > 0) {
		checkObj.each(function(index, obj) {

			var isCheck = true;

			// 当前元素的祖先class=formcontainer，判断祖先的parent是否CheckForm=0
			var formContainer = $(obj).parents(".formcontainer");
			if (formContainer.length > 0) {
				var formContainerParent = formContainer.parent();
				var formContainerParentId = formContainerParent[0].id;

				var sourceObj = $("[target='" + formContainerParentId + "']");

				if (sourceObj.css("display") == "none") {
					isCheck = false;
				}
			}

			if (isCheck) {
				obj = $(obj);
				var currentReturn = CheckControl(obj, "");
				if (!currentReturn) {
					ret = false;
				}
			}

		});
	}

	// Tab页标注
	var tabGroup = $(".tabGroup");
	if (tabGroup.length > 0) {
		tabGroup.find(".tab").each(function(index, obj) {
			var obj = $(obj);
			var targetId = obj.attr("target");

			if (targetId == undefined || obj.css("display") == "none") {
				// 不验证
			} else {
				var targetObj = $("#" + targetId);

				var errorObj = targetObj.find(".inputresult.error");
				if (errorObj.length > 0) {
					ChangeTabResult(obj, 0);
				} else {
					ChangeTabResult(obj, 1);
				}
			}

		});
	}

	return ret;
}

function ChangeTabResult(obj, isRight) {
	if (isRight == 1) {
		obj.find(".inputresult").each(function(index, obj) {
			var result = $(obj);
			result.addClass("init");
			result.removeClass("right");
			result.removeClass("error");
		});
	} else if (isRight == 0) {
		obj.find(".inputresult").each(function(index, obj) {
			var result = $(obj);
			result.removeClass("init");
			result.removeClass("right");
			result.addClass("error");
		});
	}
}

function IsReadOnly(obj) {
	var ret = false;
	if (obj.attr("readonly") == true) {
		ret = true;
	}
	return ret;
}

function CheckControl(obj, event) {

	var ret = true;

	// 隐藏的控件不验证

	// 禁用的控件不验证

	// 只读的不验证

	var minLength = obj.attr("minlength");
	if (minLength == undefined || minLength.length == 0) {
		minLength = 0;
	}
	var maxLength = obj.attr("maxlength");

	var validateRegular = obj.attr("validateregular");
	if (validateRegular == undefined || validateRegular.length == 0) {
		validateRegular = "";
	}
	var controlName = obj.attr("controlname");
	if (controlName == undefined || controlName.length == 0) {
		controlName = "";
	} else {
		controlName = "【" + controlName + "】";
	}
	var bindControl = obj.attr("bindcontrol");

	if (bindControl != undefined && bindControl.length > 0) {
		var bindControlObj = $("#" + bindControl);
		if (bindControlObj.length > 0) {

			if (event == "blur" && IsReadOnly(bindControlObj) == false) {
				// 输入完毕
				bindControlObj.blur(function() {
					ret = ShowControlResult(obj, bindControlObj, minLength,
							maxLength, validateRegular, controlName);
				});
			} else if (event == "change" && IsReadOnly(bindControlObj) == true) {
				// 选择值改变输入框
				bindControlObj.change(function() {
					ret = ShowControlResult(obj, bindControlObj, minLength,
							maxLength, validateRegular, controlName);
				});
			} else if (event.length == 0) {
				ret = ShowControlResult(obj, bindControlObj, minLength,
						maxLength, validateRegular, controlName);
			}

		}
	}

	return ret;
}

function ShowControlResult(obj, bindControlObj, minLength, maxLength,
		validateRegular, controlName) {
	var inputValue = bindControlObj.val();
	var msg = "";
	var isRight = true;

	if (minLength > 0 && inputValue.length == 0) {
		msg = controlName + "不能为空！";
		isRight = false;
	} else if (inputValue.length < minLength) {
		msg = controlName + "要满足最少" + minLength.toString() + "位";
		isRight = false;
	} else if (maxLength && inputValue.length > maxLength) {
		msg = controlName + "超出最大" + maxLength.toString() + "位";
		isRight = false;
	} else if (validateRegular.length > 0 && inputValue.length > 0) {

		if (validateRegular.indexOf("^") == 0) {
			// 直接正则验证
			var re = new RegExp(validateRegular);
			if (!re.test(inputValue)) {
				msg = controlName + "要满足当前书写格式";
				isRight = false;
			}
		} else {
			var regularArray = validateRegular.split(",");
			var regularCode = "";
			for (var i = 0; i < regularArray.length; i++) {
				if (regularArray[i] == "汉字") {
					regularCode += "\u4e00-\u9fa5";
				} else if (regularArray[i] == "字母") {
					regularCode += "a-zA-Z";
				} else if (regularArray[i] == "数字") {
					regularCode += "0-9";
				} else if (regularArray[i] == "小数后两位") {
					regularCode += "\d+(\.\d{1,2})?";
				}
			}
			if (regularCode.length > 0) {
				regularCode = "^[" + regularCode + "]+$";

				var re = new RegExp(regularCode);
				if (!re.test(inputValue)) {
					msg = controlName + "要满足(" + validateRegular + ")";
					isRight = false;
				}
			}
		}

	}

	if (isRight == true) {
		// 必须要有值才能是对勾
		if (inputValue.length > 0) {
			obj.removeClass("init");
			obj.removeClass("error");
			obj.addClass("right");
			obj.removeAttr("title");
			obj.unbind("click");
		}
	} else {
		obj.removeClass("init");
		obj.removeClass("right");
		obj.addClass("error");
		obj.attr("title", msg);
		obj.click(function() {
			TonySky.alert(msg);
		});
	}

	return isRight;
}

// 获取选择框选中的项
function CheckNumber(container) {
	var SelectNum = 0;
	var SelectList = new Array();

	var inputs = $(container).find("input")
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "checkbox") {
			if (inputs[i].checked == true) {
				SelectList[SelectNum] = inputs[i].value;
				SelectNum++;
			}
		}
	}
	return SelectList;
}

// 判断是不是选择一项
function MustSelectOne(objId) {
	var container = document.getElementById(objId);
	var selectItem = CheckNumber(container);
	if (selectItem.length != 1) {
		// alert("请选择一项！");
		return false;
	} else {
		return true;
	}
}

// 判断是不是选择
function MustSelect(objId) {
	var container = document.getElementById(objId);
	var selectItem = CheckNumber(container);
	if (selectItem.length == 0) {
		// alert("请至少选择一项！");
		return false;
	} else {
		return true;
	}
}

var onSelect = false;
function SelectAll(selectValueControlId) {
	onSelect = !onSelect;
	var container = document.getElementById(selectValueControlId);
	var inputs = container.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "checkbox") {
			inputs[i].checked = onSelect;
		}
	}

}


//属性框
function hideElement(rowId)
{
	$("#"+rowId).css("display","none");
}

function dependElement(rowId,dependParamsId,dependParamsValue)
{
	dependParamsValue=dependParamsValue.replace("default","");
	var dependParamsValueArray=dependParamsValue.split(",");
	
	$("#"+dependParamsId).change(function(){

		if($.inArray($(this).val(),dependParamsValueArray)>=0)
		{
			$("#"+rowId).css("display","");

			var c=$("#hidFormParamIds").val();
			c+=(rowId.replace("row_","")+",");
			$("#hidFormParamIds").val(c);
		}
		else
		{
			$("#"+rowId).css("display","none");
			
			var c=$("#hidFormParamIds").val();
			var reg = new RegExp(rowId.replace("row_","")+",", "g" )
			c=c.replace(reg,"");
			$("#hidFormParamIds").val(c);
		}
	});
}

function InitFormControlValue(submitFormId,keyId)
{
	$.ajax({
		type : "POST",
		async : false,
		url : FormCodeUrl + "/initFormControlValue?submitFormId=" + submitFormId + "&keyId=" + keyId,
		success : function(msg) {
			
			var listObj=eval(msg);
			
			for(var i=0;i<listObj.length;i++)
			{
				var itemObj=listObj[i];
				var key=itemObj.key;
				var value=itemObj.value;
				
				if(document.getElementById(key))
				{
					$("#"+key).val(decodeURIComponent(value));
				}
				
			}
			

			
		}

	});
}

function InitInsertValue(controlName,initValue)
{
	if(FormSubmitAction=="insert")
	{
		$.ajax({
			type : "POST",
			async : false,
			url : FormCodeUrl + "/initInsertValue?initValue=" + initValue,
			success : function(msg) {
				
				if(document.getElementById(controlName))
				{
					$("#"+controlName).val(msg);
				}
				
				
			}
	
		});
	}

}

function GetUrlValue(value) {
    var url = document.URL.split('?');
    var queryString;
    var name
    if (url.length > 1) {
        queryString = url[1].split('&');
        for (var i = 0; i < queryString.length; i++) {
            if (queryString[i].indexOf(value) > -1) {
                name = queryString[i].substring(queryString[i].indexOf("=") + 1);
                return name;
            }
        }
    }
    return "";
}